package com.soso.gae.spider.filter;

import java.io.IOException;
import java.util.TimeZone;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.soso.gae.spider.bussiness.impl.GaeSpiderBussinessImpl;
import com.soso.gae.spider.queue.api.impl.QueueServiceImpl;
import com.soso.gae.spider.service.BaseService;
import com.soso.gae.spider.service.impl.BaseServiceImpl;
import com.soso.gae.spider.service.impl.CacheServiceImpl;
import com.soso.gae.spider.service.impl.CrawlInfoServiceImpl;
import com.soso.gae.spider.service.impl.PMF;
import com.soso.spider.bussiness.SpiderBussiness;
import com.soso.spider.context.SpiderContext;

/**
 * 
 * @author speed
 *
 */
public class ContextFilter extends  com.soso.spider.filter.ContextFilter{
  
    public void doFilter(ServletRequest request, ServletResponse response, 
    		FilterChain chain) throws IOException, ServletException {
    	TimeZone.setDefault(TimeZone.getTimeZone("US/Pacific"));
    	SpiderContext ctx = SpiderContext.getInstance();
    	ctx.setRequest((HttpServletRequest)request);
    	ctx.setResponse((HttpServletResponse)response);
    	if(ctx.getBaseService()==null){
    		BaseService baseService=BaseServiceImpl.getInstance();
    		if(baseService.getPmFactory()==null){
				baseService.setPmFactory(PMF.get());
			}
    		ctx.setBaseService(baseService);
    	}
    	if(ctx.getCacheService()==null){
    		ctx.setCacheService(new CacheServiceImpl());
    	}
    	if(ctx.getQueueService()==null){
    		ctx.setQueueService(new QueueServiceImpl());
    	}
    	if(ctx.getSpiderBussiness()==null){
    		SpiderBussiness spiderBussiness=new GaeSpiderBussinessImpl();
        	spiderBussiness.setCrawlInfoService(new CrawlInfoServiceImpl());
        	ctx.setSpiderBussiness(spiderBussiness);
    	}
    	ctx.init();
     	chain.doFilter(request, response);
    	ctx.destory();
    }
	

}
